package com.goockr.batteryviewdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private Handler timeHandler;
    BatteryReceiver batteryReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        batteryReceiver = new BatteryReceiver();
        registerReceiver(batteryReceiver, intentFilter);

        final MyBatteryView view_MainBattery=(MyBatteryView)findViewById(R.id.view_MainBattery);

        //主线程的 handler 接收到 子线程的消息，然后修改TextView的显示
        timeHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int what = msg.what;
                switch (what) {
                    case 10001:
                        //根据电量绘画控件的宽度
                        view_MainBattery.rePaint(Color.WHITE,(int)(view_MainBattery.getWidth()*msg.arg2*0.01f));
                        break;
                }
            }
        };

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(batteryReceiver);
    }

    private int mBatteryLevel;
    private int mBatteryScale;
    private int isCharging=0;//1为充电状态 .。。
    class BatteryReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //判断它是否是为电量变化的Broadcast Action
            if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
                Message message = Message.obtain();
                int status=intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);//     表示是充电状态
                if(status==BatteryManager.BATTERY_STATUS_CHARGING) isCharging=1;
                else isCharging=0;

                message.what = 10001;
                //获取当前电量
                mBatteryLevel = intent.getIntExtra("level", 0);
                //电量的总刻度
                mBatteryScale = intent.getIntExtra("scale", 100);
                message.arg1= isCharging;
                message.arg2 = mBatteryLevel;
                timeHandler.sendMessage(message);

            }
        }
    }
}
